﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace SharpSoft.WPF.Controls
{
    /// <summary>
    /// DataChooserWindow.xaml 的交互逻辑
    /// </summary>
    public partial class DataChooserWindow : Window
    {
        public DataChooserWindow()
        {
            InitializeComponent();
            grid.AutoGeneratingColumn += Grid_AutoGeneratingColumn;

            grid.AutoGeneratedColumns += Grid_AutoGeneratedColumns;
            grid.SelectionChanged += Grid_SelectionChanged;
            this.Loaded += DataChooserWindow_Loaded;
        }

        private async void DataChooserWindow_Loaded(object sender, RoutedEventArgs e)
        {
            if (LoadDataOnWindowLoaded)
            {
                await loadAsync();
            }
        }

        public bool LoadDataOnWindowLoaded { get; set; } = true;

        private void Grid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SelectedValue = grid.SelectedValue;
            btn_ok.IsEnabled = (SelectedValue != null);
        }

        private void Grid_AutoGeneratedColumns(object sender, EventArgs e)
        {
            if (Headers != null)
            {//对生成的列进行排序
                List<DataGridColumn> l = new List<DataGridColumn>();
                foreach (var h in Headers)
                {
                    foreach (var item in grid.Columns)
                    {
                        if ((string)item.Header == h.Value)
                        {
                            l.Add(item);
                            break;
                        }
                    }
                }
                grid.Columns.Clear();
                foreach (var item in l)
                {
                    grid.Columns.Add(item);
                }
            }
        }


        /// <summary>
        /// 指定所有需要呈现的列
        /// </summary>
        public Dictionary<string, string> Headers { get; set; }
        private void Grid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            if (Headers != null)
            {
                if (Headers.ContainsKey(e.PropertyName))
                {
                    e.Column.Header = Headers[e.PropertyName];
                }
                else
                {
                    e.Cancel = true;
                }

            }
        }

        public event Func<string, Task<IEnumerable>> LoadData;

        public object SelectedValue { get; set; }

        private async Task loadAsync()
        {
            busy.IsBusy = true;
            try
            {
                var data = await LoadData.Invoke(txt_search.Text);
                setdata(data);
            }
            catch (Exception)
            {
                this.dlgError("发生异常。");
            }
            finally
            {
                setbusy(false);
            }


        }
        private async void btn_search_Click(object sender, RoutedEventArgs e)
        {
            await loadAsync();
        }
        void setbusy(bool isbusy)
        {
            if (Dispatcher.Thread != Thread.CurrentThread)
            {
                Dispatcher.Invoke(new Action<bool>(setbusy), isbusy);
                return;
            }
            busy.IsBusy = isbusy;
        }
        void setdata(IEnumerable data)
        {
            if (Dispatcher.Thread != Thread.CurrentThread)
            {
                Dispatcher.Invoke(new Action<IEnumerable>(setdata), data);
                return;
            }
            grid.ItemsSource = data;
            //setHeader();
        }

        private void btn_cancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void btn_ok_Click(object sender, RoutedEventArgs e)
        {
            if (this.SelectedValue == null)
            {
                this.dlgError("未选择任何数据。");
                return;
            }
            this.DialogResult = true;
        }

        private async void txt_search_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                await loadAsync();
            }

        }

        private void grid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            btn_ok_Click(null, null);
        }
    }
}
